﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PmSoft;
using PmSoft.Events;
using PmSoft.FileStorage;

namespace Modules.System.Attachment.EventModules;

[UseDI(ServiceLifetime.Singleton, typeof(IEventMoudle))]
public class AttachmentModule : IEventMoudle
{
    private readonly IEventBus eventBus;

    public AttachmentModule(IEventBus eventBus)
    {
        this.eventBus = eventBus;
    }

    public void RegisterEventHandler()
    {
        eventBus.Subscribe<PublishAttachmentEventArgs, AttachmentEventHandler>();
    }
}

[UseDI(ServiceLifetime.Scoped)]
public class AttachmentEventHandler : IEventHandler<PublishAttachmentEventArgs>
{
    private readonly AttachmentService attachmentService;
    private readonly IFileStorage fileStorage;
    private readonly ILogger logger;
    private const string tempDirectory = "temps";

    public AttachmentEventHandler(ILogger<AttachmentEventHandler> logger, AttachmentService attachmentService, IFileStorage fileStorage)
    {
        this.logger = logger;
        this.attachmentService = attachmentService;
        this.fileStorage = fileStorage;
    }

    public async Task HandleAsync(object sender, PublishAttachmentEventArgs eventArgs)
    {
        foreach (var item in eventArgs.Relationships)
        {
            if (string.IsNullOrEmpty(item.AttachmentId))
                continue;

            var attachmentInfo = attachmentService.GetAttachmentInfo(item.AttachmentId);
            if (attachmentInfo == null || !attachmentInfo.IsTemporary)
                continue;

            string tempPath = Path.Combine(Environment.CurrentDirectory, tempDirectory, attachmentInfo.Name);
            if (!File.Exists(tempPath))
                continue;

            try
            {
                var bts = File.ReadAllBytes(tempPath);
                string objectFilePath = $"{item.Directory}/{attachmentInfo.Name}";
                await fileStorage.PutFileAsync(item.BucketName, objectFilePath, bts);
                File.Delete(tempPath);
                attachmentInfo.ObjectFilePath = objectFilePath;
                attachmentInfo.IsTemporary = false;
                attachmentInfo.BucketName = item.BucketName;
                attachmentService.Update(attachmentInfo);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "发布附件失败");
            }
        }
    }
}